<?php

class CategoryModel extends Model {

    public $table = 'categories';
    public $order = '`order`';

    public static function tree($parent_id=null, $conditions=array()) {
        $tree = array();

        $children = self::children($parent_id, $conditions);
        foreach ($children as $child) {
            $child->children = self::tree($child->id, $conditions);
            $tree[] = $child;
        }

        return $tree;
    }

    public static function children($parent_id, $conditions=array()) {
        $conditions['parent_id'] = $parent_id;
        return self::build()
                ->where($conditions)
                ->query();
    }

    public static function breadcrumbs($id, $glue = ' &raquo; ') {
        $category = self::get($id);
        $breadcrumbs = array();
        while($category->parent_id>0) {
            $category = self::get($category->parent_id);
            $breadcrumbs[] = $category;
        }

        if (empty($breadcrumbs)) {
            return array();
        } else {
            return array_reverse($breadcrumbs);
        }
    }

    public static function childrenIds($id) {
        $children = self::tree($id);

        $getids = function($categories, $getids) {
            $ids = array();
            foreach ($categories as $c) {
                $ids[] = $c->id;
                $ids = array_merge($ids, $getids($c->children, $getids));
            }

            return $ids;
        };

        return $getids($children, $getids);
    }
}